package ema.tpjee.banking.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import ema.tpjee.banking.model.City;
import ema.tpjee.utils.Paging;

@Stateless
public class CityDaoImpl implements CityDao {

	@PersistenceContext(unitName = "bankunit")
	private EntityManager entityManager = null;

	public City add(City c) {
		if (find(c) == null) {
			entityManager.persist(c);
			return c;
		} else
			return c;
	}

	public City create() {
		City c = new City();
		c.setName("noname");
		entityManager.persist(c);
		return c;
	}

	public City delete(City c) {
		City result = null;
		c = find(c); //pour avoir un bean rattaché
		if (c!= null) {
			result = prior(c);
			if (result == null)
				result = next(c);
			entityManager.remove(c);
		}
		return result;
	}

	public City find(int id) {
		return entityManager.find(City.class, id);
	}

	public City find(City c) {
		return entityManager.find(City.class, c.getId());
	}

	/**
	 * retourne la première City correspondant au code postal passé en paramètre
	 */
	public City find(String zipcode) {
		return (City) (entityManager.createNamedQuery("allcitiesbyzipcode")
				.setParameter("zipcode", zipcode).getResultList().get(0));
	}

	public City first() {
		return getList().get(0);
	}

	@SuppressWarnings("unchecked")
	public List<City> getList() {
		return entityManager.createNamedQuery("allcities").getResultList();
	}

	public City last() {
		List<City> cities = getList();
		return cities.get(cities.size() - 1);
	}

	public City merge(City c) {
		return entityManager.merge(c);
	}

	public City next(City c) {
		return Paging.next(getList(), c);
	}

	
	
	public List<City> populate() {
		City c1 = new City("Nîmes", "30000", "France");
		add(c1);
		City c2 = new City("Montpellier", "34000", "France");
		add(c2);
		City c3 = new City("Alès", "30000", "France");
		add(c3);
		return getList();
	}

	public City prior(City c) {
		return Paging.prior(getList(), c);
	}

	public Boolean isSame(City a, City b) {
		return a.getId() == b.getId();
	}

}
